package org.vt.scheduleapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class LocLister extends ListActivity {
	    
    private LocReader reader;
    private LocWriter writer;
    private List<Loc> locs;
    private Context Ctx;
    
	public void onCreate(Bundle savedInstanceState) {
        Ctx = this;
		super.onCreate(savedInstanceState);
        setContentView(R.layout.displocs);
        registerForContextMenu(getListView());
        reader = new LocReader(this);
        locs= new ArrayList<Loc>();
		try {
			locs = reader.getAllLocs();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String[] locStrings = new String[locs.size()];
        int count = 0;
        for(Loc l : locs)
        {
        	locStrings[count]=l.toString();
        	count++;
        }
        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, locStrings));
        
	}
	
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        AlertDialog.Builder alert = new AlertDialog.Builder(
				LocLister.this);
		alert.setTitle("Delete?");
		alert.setMessage("Do you want to delete this location?");

		// Set an EditText view to get user input
		//final EditText input = new EditText(ListLocations.this);
		//alert.setView(input);
		final int pos = position;
		final View v2 = v;
		alert.setPositiveButton("YES",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
							locs.remove(pos);
							writer = new LocWriter(v2.getContext());
							try {
								writer.writeLoc(locs);
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							Intent myIntent = new Intent(v2.getContext(),
									LocLister.class);
							startActivityForResult(myIntent, 0);
					}
		});
		alert.setNegativeButton("NO",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
						
					}
		});
		alert.show();
    }
	@Override
	public void onBackPressed(){
		Intent myIntent = new Intent(Ctx, LocationsActivity.class);
		startActivityForResult(myIntent, 0);
	}
}